package cn.yunsenlin.formula.cloud.mould;

import cn.yunsenlin.formula.cloud.responsibility.ResponseResponsibilityHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static cn.yunsenlin.formula.cloud.responsibility.ResponseResponsibilityHandler.start;

/**
 * controller 模板模式
 */
public abstract class ControllerMould {
    private final Logger logger = LoggerFactory.getLogger(ControllerMould.class);

    private ResponseResponsibilityHandler[] handlers;

    protected ControllerMould(ResponseResponsibilityHandler... handlers) {
        this.handlers = handlers;
    }

    /**
     * 添加一些list 信息
     *
     * @param handlerList 责任链
     */
    protected void handler(List<ResponseResponsibilityHandler> handlerList) {
        //重载来获得责任链，设置更多功能
    }

    /**
     * 启动责任链
     *
     * @param response http响应
     * @param objects  传入参数
     * @param <T>      泛型
     * @return 结果
     */
    @SuppressWarnings("unchecked")
    public <T> List<T> startUpArray(HttpServletResponse response, Object... objects) {
        Object result = startUp(response, objects);
        return result == null ? null : (List<T>) result;
    }

    /**
     * 启动责任链
     *
     * @param response http响应
     * @param objects  传入参数
     * @param <T>      泛型
     * @return 结果
     */
    @SuppressWarnings("unchecked")
    public <T> T startUpObject(HttpServletResponse response, Object... objects) {
        Object result = startUp(response, objects);
        return result == null ? null : (T) result;
    }

    private Object startUp(HttpServletResponse response, Object... objects) {
        logger.debug("response responsibility handler start up");
        List<ResponseResponsibilityHandler> list = new ArrayList<>(Arrays.asList(handlers));
        handler(list);
        Object result = start(list, response, objects);
        logger.debug("response responsibility handler end");
        return result;
    }

}
